package com.gongpingjialoan.activity.particular;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.category.CategoryActivity;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.ValueReportActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.activity.sell.FreeSellCarActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.DataManager;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.AssPerfence;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.UserLocation;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.DatePickerDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

public class FirstActivity extends BaseActivity implements View.OnClickListener{
    private final int REQUEST_CITY_FRAGMENT = 1;
    private final int REQUEST_BRAND = 2;
    private static final int REQUEST_LOAN = 3;
    private static final int HISTROY_LOGIN = 4;
    private static final int EVAL_HISTORY = 5;
    private static final int FINISH = 6;
    private String mBrandSlug,mBrandName,mModelSlug,mModelName,mModelDetailSlug,mModelDetailName;
    private String mModelThumbnail;
    private String maxyear = null,minyear = null;
    private String mYear,mMonth;
    private boolean isHistory = false;

    private String mMile;
    private TextView cityT,mTxtBrand,mTxtDate,mileTypeTextView;
    private TextView submitT,historyT;
    private EditText mEdtMile;

    private NetDataJson addHistoryNet,mNetModelDetail;

    /**
     * 日期选择弹框
     */
    private DatePickerDialog dateDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        setSwipeEnagle();
        initView();
    }

    private void initView() {
        findViewById(R.id.title_back).setVisibility(View.GONE);
        setTitle("汽车分期估值");
        AssPerfence assPerfence = AssPerfence.getInstance();
        assPerfence.load();

        mTxtBrand = (TextView) findViewById(R.id.txt_model);
        mTxtDate = (TextView) findViewById(R.id.txt_year);
        mEdtMile = (EditText) findViewById(R.id.editText);
        cityT = (TextView) findViewById(R.id.txt_city);
        mileTypeTextView = (TextView) findViewById(R.id.mile_type);
        submitT = (TextView) findViewById(R.id.submit);
        historyT = (TextView) findViewById(R.id.history);

        mTxtBrand.setOnClickListener(this);
        mTxtDate.setOnClickListener(this);
        cityT.setOnClickListener(this);
        submitT.setOnClickListener(this);
        historyT.setOnClickListener(this);

        initListener();
        if (UserLocation.getInstance().isIslocation()) {
            cityT.setText(UserLocation.getInstance().getCity());
        } else {
            cityT.setText(((GPJApplication) getApplication()).getCityData().mCurrentCity);
        }
        intAssHistory();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.history:
                intent = new Intent(mySelf, FreeSellCarActivity.class);
                startActivityForResult(intent, EVAL_HISTORY);
                break;
            case R.id.submit:
                    submit();
                break;
            case R.id.txt_model:
                if (!DataManager.getInstance().getLoadingDataSuccess()) {
                    Toast.makeText(mySelf, "数据未加载成功,请检查网络是否连接!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                intent = new Intent();
                intent.setClass(mySelf, CategoryActivity.class);
                intent.putExtra(Const.BRAND_NAME_KEY, mBrandName);
                intent.putExtra(Const.BRAND_SLUG_KEY, mBrandSlug);
                intent.putExtra(Const.MODEL_NAME_KEY, mModelName);
                intent.putExtra(Const.MODEL_SLUG_KEY, mModelSlug);
                intent.putExtra(Const.MODEL_DETAIL_NAME_KEY, mModelDetailName);
                intent.putExtra(Const.MODEL_DETAIL_SLUG_KEY, mModelDetailSlug);

                intent.putExtra("needModelDetailFragment", true);
                startActivityForResult(intent, REQUEST_BRAND);

                break;
            case R.id.txt_year:
                if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                        || mTxtBrand.getText().toString().equals("请选择您的爱车型号")) {
                    Toast.makeText(mySelf, "请选择车辆型号!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (null != dateDialog && maxyear != null) {
                    dateDialog.show();
                } else {
                    Toast.makeText(mySelf, "上牌时间数据加载中!",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.txt_city:
                intent = new Intent();
                intent.putExtra("needProvince", false);
                intent.setClass(mySelf, CityActivity.class);
                startActivityForResult(intent, REQUEST_CITY_FRAGMENT);
                break;
        }
    }

    private void isClick(){
        submitT.setEnabled(false);
        submitT.setBackgroundResource(R.color.text_grey);
        if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                || mTxtBrand.getText().toString().equals("请选择") || mTxtBrand.getText().toString().equals("请选择您的爱车型号")) {
//            Toast.makeText(mySelf, "请选择车辆型号!",
//                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(mTxtDate.getText().toString()) || "请选择".equals(mTxtDate.getText().toString()) || "上牌时间".equals(mTxtDate.getText().toString())) {
//            Toast.makeText(mySelf, "请选择上牌时间!",
//                    Toast.LENGTH_SHORT).show();
            return;
        }

        mMile = mEdtMile.getText().toString();

        Double mile = -1.0;

        if (TextUtils.isEmpty(mMile)) {
//            Toast.makeText(mySelf, "请输入行驶里程!",
//                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (mMile.length() > 5) {
            Toast.makeText(mySelf,
                    "请输入正确的公里数，小数和整数均不能超过2位数!", Toast.LENGTH_SHORT)
                    .show();
            return;
        }


        try {
            mile = Double.valueOf(mMile);
        } catch (NumberFormatException e) {
            Toast.makeText(mySelf, "请填写正确的行驶里程（0-100万公里）",
                    Toast.LENGTH_SHORT).show();
            return;

        }

        if (mile < 0 || mile > 100) {
            Toast.makeText(mySelf, "请填写正确的行驶里程（0-100万公里）",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        mMile = mile + "";

        submitT.setEnabled(true);
        submitT.setBackgroundResource(R.color.blue_3fbbff);
    }

    private void submit() {
        // 将评估的数据存放起来,后面的页面用到的数据,基本都是从这边取的,除了CarListActivity(暂时是这样的)
        AssessmentData data = AssessmentData.getInstance();
        data.clear();
        data.setBrandName(mBrandName);
        data.setBrandSlug(mBrandSlug);
        data.setMile(mMile);
        data.setModelDetailName(mModelDetailName);
        data.setModelDetailSlug(mModelDetailSlug);
        data.setModelName(mModelName);
        data.setModelSlug(mModelSlug);
        data.setModelThumbnail(mModelThumbnail);
        data.setMonth(mMonth);
        data.setCity(cityT.getText().toString());
        data.setCar_id("");
        data.setYear(mYear);

        //添加估值历史
        initAddHistory(data);
        AssPerfence per = AssPerfence.getInstance();
        per.setBrandName(mBrandName);
        per.setBrandSlug(mBrandSlug);
        per.setMile(mMile);
        per.setModelDetailName(mModelDetailName);
        per.setModelDetailSlug(mModelDetailSlug);
        per.setModelName(mModelName);
        per.setModelSlug(mModelSlug);
        per.setModelThumbnail(mModelThumbnail);
        per.setMonth(mMonth);
        per.setYear(mYear);
        per.setMaxyear(maxyear);
        per.setMinyear(minyear);
        per.setCity(cityT.getText().toString());
        per.commit();
        isHistory = true;


        String url =
                "http://m.gongpingjia.com/m/mobile/" + data.getBrandSlug() + "/" + data.getModelSlug() + "/"
                        + data.getModelDetailSlug() + "/" + data.getYear() + "-" + data.getMonth() + "/" + data.getMile()
                        + "/";
        Utils.LogD("web url = " + url);
        Intent it = new Intent();
        it.putExtra("url", url);
        it.putExtra("title", "估值报告");
        it.putExtra("content", "");
        it.setClass(mySelf, ValueReportActivity.class);
        startActivity(it);
        startActivityForResult(it,FINISH);
    }

    private void initAddHistory(AssessmentData assessmentData) {
        addHistoryNet = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                //刷新
            }
        });
        addHistoryNet.setUrl(API.addHistoryCars);
        addHistoryNet.addParam("brand", assessmentData.getBrandSlug());
        addHistoryNet.addParam("model", assessmentData.getModelSlug());
        addHistoryNet.addParam("model_detail", assessmentData.getModelDetailSlug());
        addHistoryNet.addParam("year", assessmentData.getYear());
        addHistoryNet.addParam("month", assessmentData.getMonth());
        addHistoryNet.addParam("mile", assessmentData.getMile());
        addHistoryNet.addParam("city", assessmentData.getCity());
        addHistoryNet.request("post");
    }

    public void intAssHistory() {
        AssPerfence assPerfence = AssPerfence.getInstance();
        assPerfence.load();
        if (TextUtils.isEmpty(assPerfence.getBrandName())) {
            return;
        }
        isHistory = true;
        mBrandSlug = assPerfence.getBrandSlug();
        mBrandName = assPerfence.getBrandName();
        mModelSlug = assPerfence.getModelSlug();
        mModelName = assPerfence.getModelName();
        mModelDetailName = assPerfence.getModelDetailName();
        mModelDetailSlug = assPerfence.getModelDetailSlug();
        mModelThumbnail = assPerfence.getModelThumbnail();
        if (mModelDetailName == null) {
            mTxtBrand.setText(mModelName);
        } else {
            mTxtBrand.setText(mModelName + " " + mModelDetailName);
        }
        mYear = assPerfence.getYear();
        mMonth = assPerfence.getMonth();
        if (TextUtils.isEmpty(mMonth)) {
            mTxtDate.setText(mYear + "年");
        } else {
            mTxtDate.setText(mYear + "年" + mMonth + "月");
        }
        // mTxtDate.setTextColor(Color.parseColor("#666666"));
        cityT.setText(assPerfence.getCity());
        double m = Double.parseDouble(assPerfence.getMile());
        if (m % 1 == 0) {
            mEdtMile.setText((int) m + "");
        } else {
            mEdtMile.setText(assPerfence.getMile());
        }
        mileTypeTextView.setText("万公里");
        dateDialog = new DatePickerDialog(mySelf);
        dateDialog.setMinMonth(1);
        dateDialog.setMaxMonth(12);
        dateDialog.setDialogCallBack(new DatePickerDialog.OnDialogCallBack() {

            @Override
            public void onSelectResult(String year, String month, String day) {
                mYear = year;
                mMonth = month;
                if (TextUtils.isEmpty(month)) {
                    mTxtDate.setText(year + "年");
                } else {
                    mTxtDate.setText(year + "年" + month + "月");
                }
                //mTxtDate.setTextColor(Color.parseColor("#666666"));
            }


        });
        maxyear = assPerfence.getMaxyear();
        minyear = assPerfence.getMinyear();
        dateDialog.setMonthPickerVisibility(View.VISIBLE);
        dateDialog.setMinYear(Integer.parseInt(minyear));
        dateDialog.setMaxYear(Integer.parseInt(maxyear));
    }

    private void initListener() {
        mTxtBrand.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mTxtBrand.getText().toString()) || "请选择您的爱车型号".equals(mTxtBrand.getText().toString())) {
                    mTxtBrand.setTextColor(Color.parseColor("#999999"));
                } else {
                    mTxtBrand.setTextColor(Color.parseColor("#333333"));
                }
                isClick();
            }
        });
        mTxtDate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mTxtDate.getText().toString()) || "上牌时间".equals(mTxtDate.getText().toString()) || "请选择".equals(mTxtDate.getText().toString())) {
                    mTxtDate.setTextColor(Color.parseColor("#999999"));
                } else {
                    mTxtDate.setTextColor(Color.parseColor("#333333"));
                }
                isClick();
            }
        });


        mEdtMile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mEdtMile.getText().toString())) {
                    mEdtMile.setTextColor(Color.parseColor("#999999"));
                    mileTypeTextView.setTextColor(Color.parseColor("#999999"));
                    mileTypeTextView.setText("行驶里程");
                } else {
                    mEdtMile.setTextColor(Color.parseColor("#333333"));
                    mileTypeTextView.setTextColor(Color.parseColor("#333333"));
                    mileTypeTextView.setText("万公里");
                }
                isClick();
            }
        });
        cityT.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(cityT.getText().toString()) || "上牌城市".equals(cityT.getText().toString())) {
                    cityT.setTextColor(Color.parseColor("#999999"));
                } else {
                    cityT.setTextColor(Color.parseColor("#333333"));
                }
                isClick();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 城市选择回调
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    String city = b.getString("city");
                    if (!TextUtils.isEmpty(city)) {
                        cityT.setText(city);
                    }
                    break;
                // 车型选择回调
                case REQUEST_BRAND:
                    Bundle bundle = data.getExtras();
                    onBrandSelceted(bundle);
                    break;
                case REQUEST_LOAN:
                    submit();
                    break;
                case HISTROY_LOGIN:
                    Intent intent = new Intent(mySelf, FreeSellCarActivity.class);
                    startActivityForResult(intent, EVAL_HISTORY);
                    break;
                case FINISH:
                    finish();
                    break;
                case EVAL_HISTORY:
                    AssessmentData mAssessData = AssessmentData.getInstance();
                    mBrandSlug = mAssessData.getBrandSlug();
                    mBrandName = mAssessData.getBrandName();
                    mModelSlug = mAssessData.getModelSlug();
                    mModelName = mAssessData.getModelName();
                    mModelDetailSlug = mAssessData.getModelDetailSlug();
                    mModelDetailName = mAssessData.getModelDetailName();
                    mTxtBrand.setText(mAssessData.getModelName() + " " + mAssessData.getModelDetailName());
                    mTxtDate.setText(mAssessData.getYear() + "年" + mAssessData.getMonth() + "月");
                    mYear = mAssessData.getYear();
                    mMonth = mAssessData.getMonth();
                    getMaxMinYear();

                    double mile = 0.00;
                    try {
                        mile = Double.parseDouble(mAssessData.getMile());
                    } catch (NumberFormatException e) {
                    }
                    //保留一位小数
                    BigDecimal bd = new BigDecimal(mile + "");
                    bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
                    mEdtMile.setText(bd.toString());
                    mEdtMile.setSelection(bd.toString().length());
                    cityT.setText(mAssessData.getCity());
                    break;
                default:
                    break;
            }
        }
    }

    private void getMaxMinYear() {
        if (mNetModelDetail == null) {
            mNetModelDetail = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {

                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    if (null == json) {
                        return;
                    }

                    try {
                        JSONArray detail = json.getJSONArray("detail_model");
                        if (null == detail) {
                            return;
                        }
                        for (int i = 0; i < detail.length(); i++) {
                            JSONObject jo = detail.getJSONObject(i);
                            if (null != jo) {
                                if (mModelDetailSlug.equals(jo.getString("detail_model_slug"))) {
                                    minyear = jo.getString("min_reg_year");
                                    maxyear = jo.getString("max_reg_year");
                                    break;
                                }
                            }
                        }
                    } catch (JSONException e) {

                    }

                    // 上牌年份选择弹框
                    dateDialog = new DatePickerDialog(mySelf);
                    dateDialog.setMinMonth(1);
                    dateDialog.setMaxMonth(12);

                    dateDialog.setDialogCallBack(new DatePickerDialog.OnDialogCallBack() {

                        @Override
                        public void onSelectResult(String year, String month, String day) {
                            mYear = year;
                            mMonth = month;
                            if (TextUtils.isEmpty(month)) {
                                mTxtDate.setText(year + "年");
                            } else {
                                mTxtDate.setText(year + "年" + month + "月");
                            }
                        }

                    });
                    //    dateLicenseText.setTextColor(Color.parseColor("#666666"));
                    dateDialog.setMonthPickerVisibility(View.VISIBLE);
                    dateDialog.setMinYear(Integer.parseInt(minyear));
                    dateDialog.setMaxYear(Integer.parseInt(maxyear));
                }
            });
        }
        mNetModelDetail.setUrl(API.modelDetail);
        mNetModelDetail.addParam("brand", mBrandSlug);
        mNetModelDetail.addParam("model", mModelSlug);
        mNetModelDetail.request("get");
    }

    // 选择完车型后,调用这辆
    public void onBrandSelceted(Bundle bundle) {
        maxyear = null;
        minyear = null;
        mBrandSlug = bundle.getString("brandSlug");
        mBrandName = bundle.getString("brandName");
        mModelSlug = bundle.getString("modelSlug");
        mModelName = bundle.getString("modelName");
        mModelDetailName = bundle.getString("modelDetailName");
        mModelDetailSlug = bundle.getString("modelDetailSlug");
        mModelThumbnail = bundle.getString("modelThumbnail");

        // 查询二手车,选择车型后,车辆型号TextView的展示
        if (mModelDetailName == null) {
            mTxtBrand.setText(mModelName);
        } else {
            mTxtBrand.setText(mModelName + " " + mModelDetailName);
        }
        //mTxtBrand.setTextColor(Color.parseColor("#666666"));

        // delete the date data if it is not null
        mTxtDate.setText("请选择");
        // mTxtDate.setTextColor(Color.parseColor("#18A0E0"));
        // 上牌年份选择弹框
        dateDialog = new DatePickerDialog(mySelf);
        dateDialog.setMinMonth(1);


        dateDialog.setMaxMonth(12);

        dateDialog.setDialogCallBack(new DatePickerDialog.OnDialogCallBack() {

            @Override
            public void onSelectResult(String year, String month, String day) {
                mYear = year;
                mMonth = month;
                if (TextUtils.isEmpty(month)) {
                    mTxtDate.setText(year + "年");
                } else {
                    mTxtDate.setText(year + "年" + month + "月");
                }
                // mTxtDate.setTextColor(Color.parseColor("#666666"));
            }


        });

        // // 如果是评估我的车,上牌年份的日期从返回的数据bundle中取
        // if (radioG.getCheckedRadioButtonId() == R.id.radio_left)
        // {
        maxyear = bundle.getString("maxyear");
        minyear = bundle.getString("minyear");

        dateDialog.setMonthPickerVisibility(View.VISIBLE);
        dateDialog.setMinYear(Integer.parseInt(minyear));
        dateDialog.setMaxYear(Integer.parseInt(maxyear));
        if (maxyear == null) {
            Toast.makeText(mySelf, "没有可选的上牌时间!", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        mEdtMile.setText(null);

        if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                || mTxtBrand.getText().toString().equals("请选择您的爱车型号")) {
            Toast.makeText(mySelf, "请选择车辆型号!",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (null != dateDialog && maxyear != null) {
            dateDialog.show();
        } else {
            Toast.makeText(mySelf, "上牌时间数据加载中!",
                    Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (addHistoryNet != null) {
            addHistoryNet.cancelTask();
            addHistoryNet = null;
        }
        if (mNetModelDetail != null) {
            mNetModelDetail.cancelTask();
            mNetModelDetail = null;
        }
        mHandler.removeCallbacks(runnable);
    }
    private Toast mToast;
    private boolean isExit = false;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            isExit = false;
        }
    };
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                mToast = Toast.makeText(this, "再按一次退出程序",
                        Toast.LENGTH_SHORT);
                mToast.show();
                mHandler.postDelayed(runnable, 2000);
            } else {
                mToast.cancel();
                StepMonitor.getInstance().addMonitorSend(new Monitor("enter", "exit", System.currentTimeMillis(), 1f));
                StepMonitor.getInstance().isClose = true;
                finish();
//
            }

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}